package com.hans.scala

import scala.collection.mutable

class ChecksumAccumulator {
  println("call ChecksumAccumulator class.")
  private var sum = 0
  def add(b: Byte) { sum += b }
  def checksum(): Int = ~(sum & 0xFF) + 1
}

//单例对象不带参数，不能new 单例为java中的静态类
object ChecksumAccumulator {
  val cache = mutable.Map[String, Int]()

  def calculate(s: String): Int = {
    if (cache.contains(s)) {
      cache(s)
    } else {
      val acc = new ChecksumAccumulator()
      for (c <- s)
        acc.add(c.toByte)
      val cs = acc.checksum()
      cache += (s -> cs)
      cs
    }
  }

}

//孤立对象
object StandaloneObject {
  println("this is stand alone object.")
}

object Summer {
  def main(args: Array[String]) {
    val ca = ChecksumAccumulator

    StandaloneObject
    
    for (arg <- Array("Hans", "JuntaoZhang", "JuntaoZhang"))
      println(ca.calculate(arg))
    println(ca.cache)

  }

}


